/* eslint-disable array-callback-return */
import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Input, Select, Spin, message } from 'antd';
import { connect } from 'dva';
import Area from '../../../components/Area';

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ supplier }) => ({
  supplier,
}))
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fetching: false,
      provCityAreaList: [],
      backList: [],
    };
  }

  componentDidMount = () => {
    this.getAreaList(null, data => {
      data.map(item => {
        const temp = item;
        temp.label = item.areaName;
        temp.value = item.areaId;
        temp.isLeaf = false;
      });
      this.setState({ provCityAreaList: data });
    });
  };

  getData = (value, id) => {
    const tempAreaId = value.key;
    const { form } = this.props;
    if (id) {
      form.setFieldsValue({ [id]: { key: tempAreaId } });
      this.setState({ [id]: tempAreaId });
    }
  };

  // 查询省市区
  getAreaList = (areaId, callback) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'supplier/queryNmAreaByParent',
      payload: { parentId: areaId },
    }).then(res => {
      if (res.success && res.data.length) {
        callback(res.data);
      } else {
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });
  };

  searchbankId = e => {
    const newBack = [];
    const { bankList } = this.props;
    this.setState({ fetching: true });
    bankList.map(item => {
      for (let i = 0; i < item.itemName.length; i += 1) {
        for (let j = 0; j < e.length; j += 1) {
          if (e[j] === item.itemName[i]) {
            newBack.push(item);
          }
        }
      }
    });
    const newBackList = [];
    const obj = {};
    for (let i = 0; i < newBack.length; i += 1) {
      if (!obj[newBack[i].itemCode]) {
        newBackList.push(newBack[i]);
        obj[newBack[i].itemCode] = true;
      }
    }
    this.setState({
      backList: newBackList,
    });
  };

  loadAreaData = selectedOptions => {
    const { provCityAreaList } = this.state;
    const areaLevel = selectedOptions[selectedOptions.length - 1].areaNature;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    const parentId = selectedOptions[selectedOptions.length - 1].areaId;
    if (areaLevel === 2) {
      return;
    }
    targetOption.loading = true;
    const childrenData = [];
    this.getAreaList(parentId, data => {
      data.map(item => {
        const temp = item;
        if (item.areaLevel < 2) {
          temp.isLeaf = false;
        }
        temp.label = item.areaName;
        temp.value = item.areaId;
        childrenData.push(item);
      });
    });
    setTimeout(() => {
      targetOption.loading = false;
      targetOption.children = childrenData;
      this.setState({
        provCityAreaList: [...provCityAreaList],
      });
    }, 1000);
  };

  render() {
    const { fetching, backList } = this.state;
    const {
      form: { getFieldDecorator },
    } = this.props;
    // 表单布局
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };

    return (
      <Form layout="vertical">
        <Row gutter={64}>
          <Col {...colProps}>
            <FormItem label="城市">
              {getFieldDecorator('areaId', {
                rules: [{ required: true, message: '请选择' }],
              })(<Area labelInValue onChange={value => this.getData(value, 'areaId')} />)}
            </FormItem>
          </Col>
          <Col {...colProps}>
            <FormItem label="银行">
              {getFieldDecorator('bankId', {
                rules: [{ required: true, message: '请选择' }],
              })(
                <Select
                  placeholder="请输入关键字检索"
                  style={{ width: '100%' }}
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                  onSearch={this.searchbankId}
                  notFoundContent={fetching ? <Spin size="small" /> : null}
                >
                  {backList.length
                    ? backList.map(options => (
                        <Option key={options.itemCode}>{options.itemName}</Option>
                      ))
                    : null}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col {...colProps}>
            <FormItem label="开户行">
              {getFieldDecorator('openBank', {
                rules: [{ required: true, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength="100" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={64}>
          <Col {...colProps}>
            <FormItem label="银行账号">
              {getFieldDecorator('bankAcco', {
                rules: [
                  { required: true, message: '最大长度不超过25的数字', pattern: /^\d{1,25}$/ },
                ],
              })(<Input placeholder="请输入" maxLength={25} />)}
            </FormItem>
          </Col>
          <Col {...colProps}>
            <FormItem label="开户单位名称">
              {getFieldDecorator('accoHolderName', {
                rules: [{ required: true, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength="100" />)}
            </FormItem>
          </Col>
          <Col {...colProps}>
            <FormItem label="备注">
              {getFieldDecorator('remark', {
                rules: [{ required: false, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength="200" />)}
            </FormItem>
          </Col>
        </Row>
      </Form>
    );
  }
}
const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
